// ==========================================================
// ===                    INTERRUPT                       ===
// ==========================================================
//External Interrupts: 2 (interrupt 0), 3 (interrupt 1)
//                     18 (interrupt 5),19 (interrupt 4)
//                     20 (interrupt 3), 21 (interrupt 2)
// ==========================================================
//增量式-M法码盘测速，原理如下：
//PinA:下降沿触发外部中断
//PinB:若A相下降沿触发,判断B相:若出现LOW电平,为正脉冲计数器加1
//                             若出现HIGH电平,为负脉冲计数器减1
//码盘统一成前进方向
// ==========================================================
#define PinA_left 18   
#define PinB_left 22  
#define PinA_right 19 
#define PinB_right 23 

int count_left = 0;   
int count_right = 0;  

void Code_left()
{ 
  if(digitalRead(PinB_left) == 0)  
    count_left += 1; 
  else
    count_left -= 1;
}
void Code_right()
{
  if(digitalRead(PinB_right) == 0)  
    count_right -= 1;
  else
    count_right += 1;  
}
void setup()
{
  Serial.begin(115200);        // opens serial port
  attachInterrupt(5, Code_left, FALLING);//小车左车轮编码器下降沿触发
  attachInterrupt(4, Code_right, FALLING);
}
int time;
float speeds;
void loop()
{
  if(millis()-time>30)
  {
    detachInterrupt(5); // 关闭外部中断0
    detachInterrupt(4); // 关闭外部中断1
    speeds=(count_left + count_right)*0.5;
    Serial.print(count_left);//副调被调量
    Serial.print(" ");
    Serial.println(count_right);//副调被调量
    count_left = 0;       //编码器计数清零
    count_right = 0;
    attachInterrupt(5, Code_left, FALLING);//小车左车轮编码器下降沿触发
    attachInterrupt(4, Code_right, FALLING);
    time=millis();
  }
}

